package com.yiidata.rpc.hrpc;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.ProtocolSignature;
import org.apache.hadoop.ipc.RPC;

import java.io.IOException;
import java.net.BindException;

/**
 * <pre>
 *
 * Created by zhenqin.
 * User: zhenqin
 * Date: 2018/1/6
 * Time: 11:33
 * Verdor: NowledgeData
 * To change this template use File | Settings | File Templates.
 *
 * </pre>
 *
 * @author zhenqin
 */
public class HadoopRpcHelloWorldServer implements HadoopRpcProtocol {

    /**
     * Hadoop RPC 要求这个方法。 返回值代表相同版本， 不同返回值不能调用
     * @param protocol
     * @param clientVersion
     * @return 返回值代表相同版本， 不同返回值不能调用
     * @throws IOException
     */
    @Override
    public long getProtocolVersion(String protocol, long clientVersion) throws IOException {
        return versionID;
    }

    @Override
    public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int clientMethodsHash) throws IOException {
        return new ProtocolSignature(versionID, null);
    }

    @Override
    public Message sayHello(User user) {
        System.out.println("exec hello, " + user.getName());
        return new Message("hello, " + user.getName());
    }

    public static void main(String[] args) {
        RPC.Server rpcServer = null;
        try {
            rpcServer = new RPC.Builder(new Configuration())
                    .setProtocol(HadoopRpcProtocol.class)
                    .setInstance(new HadoopRpcHelloWorldServer())
                    .setBindAddress("0.0.0.0")
                    .setPort(8088)
                    .setNumHandlers(10)
                    .build();

            System.out.println("hadoop rpc server started on : " +
                    "0.0.0.0:8088");
            rpcServer.start();
        } catch (final BindException e) {
            throw new IllegalArgumentException(e);
        } catch (final IOException e) {
            throw new IllegalStateException("unable to create rpc server", e);
        }
    }
}
